package com.telit.uav.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.telit.common.constant.MsgIdentificationConstants;
import com.telit.common.entity.DataReturn;
import com.telit.common.util.RedisUtils;
import com.telit.communicate.dto.MsgProcessPathDTO;
import com.telit.communicate.dto.SendMessageDTO;
import com.telit.communicate.feign.RemoteCommunicateService;
import com.telit.uav.dto.MsgInfoDTO;
import com.telit.uav.dto.TrackInfoDTO;
import com.telit.uav.dto.UpAndDownLineDTO;
import com.telit.uav.entity.AppUavTrackDetail;
import com.telit.uav.service.AppUavTrackDetailService;
import com.telit.uav.service.UavQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


/**
 * @author zhouyu
 * @description 无人机端websocket消息处理
 */
@RestController
@Slf4j
public class UavMessageProcessController implements ApplicationRunner {

    @Autowired
    private AppUavTrackDetailService appUavTrackDetailService;

    @Autowired
    private RemoteCommunicateService communicateFeignClient;

    @Autowired
    private UavQueryService uavQueryService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //单独启动线程，防止项目启动失败
        new Thread(() -> {
            log.info("无人机端websocket消息处理线程启动");
            MsgProcessPathDTO msgProcessPathDTO = new MsgProcessPathDTO();
            msgProcessPathDTO.setSystemName("FIREPROOF");
            msgProcessPathDTO.setMsgSource("UAV");
            msgProcessPathDTO.setMessageProcessPath("http://yichang-uav/uav/messageProcess");
            msgProcessPathDTO.setUpAndDownProcessPath("http://yichang-uav/uav/upAndDownProcess");
            communicateFeignClient.subscribeMsgProcess(msgProcessPathDTO);
        }).start();
        //服务异常结束 回调方法取消订阅
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            MsgProcessPathDTO msgProcessPathDTO = new MsgProcessPathDTO();
            msgProcessPathDTO.setSystemName("FIREPROOF");
            msgProcessPathDTO.setMsgSource("UAV");
            communicateFeignClient.unSubscribeMsgProcess(msgProcessPathDTO);
        }));
    }


    @PostMapping(value = "/messageProcess", produces = "application/json;charset=UTF-8")
    public DataReturn messageProcess(@RequestBody MsgInfoDTO msgInfoDTO) {
        TrackInfoDTO trackInfoDTO = JSONObject.parseObject(msgInfoDTO.getMsg(), TrackInfoDTO.class);
        String pointCollection = trackInfoDTO.getPointCollection();
        pointCollection = pointCollection.replaceAll("\\{", "[").replaceAll("\\}", "]").replaceAll("\"latitude\":",
                "").replaceAll("\"longitude\":", "");
        pointCollection = "[" + pointCollection + "]";
        trackInfoDTO.setPointCollection(pointCollection);
        RedisUtils.setBoundHash(String.valueOf(trackInfoDTO.getTaskId()), msgInfoDTO.getUserId().split("_")[0],
                trackInfoDTO.getPointCollection());

        //飞行时间秒转成xx:xx:xx
        String convertTime = DateUtil.secondToTime(Integer.parseInt(trackInfoDTO.getFlyTime()));
        //xx:xx:xx转换成XX分钟XX秒
        String[] convertTimeArr = convertTime.split(":");
        StringBuffer finalConvertTime = new StringBuffer();
        if (!StringUtils.isEmpty(convertTimeArr[0])) {
            finalConvertTime.append(convertTimeArr[0] + "小时");
        }
        if (!StringUtils.isEmpty(convertTimeArr[1])) {
            finalConvertTime.append(convertTimeArr[1] + "分钟");
        }
        if (!StringUtils.isEmpty(convertTimeArr[2])) {
            finalConvertTime.append(convertTimeArr[2] + "秒");
        }
        //覆盖原来的值
        trackInfoDTO.setFlyTime(finalConvertTime.toString());

        //推送消息到web端
        SendMessageDTO sendMessageDTO = new SendMessageDTO();
        sendMessageDTO.setFlag("web");
        sendMessageDTO.setMsg(JSON.toJSONString(
                DataReturn.ok(MsgIdentificationConstants.UAV_REAL_TIME_TRACKING, trackInfoDTO)));
        communicateFeignClient.sendMsg(sendMessageDTO);

        //保存实时轨迹信息到detail表
        AppUavTrackDetail appUavTrackDetail = new AppUavTrackDetail();
        BeanUtils.copyProperties(trackInfoDTO, appUavTrackDetail, "userId");
        appUavTrackDetail.setUserId(Long.parseLong(msgInfoDTO.getUserId().split("_")[0]));
        String uavName = uavQueryService.queryNameByCode(trackInfoDTO.getUavCode());
        appUavTrackDetail.setUavName(uavName);
        if (StringUtils.hasText(uavName)) {
            appUavTrackDetailService.uploadRealTimeTrack(appUavTrackDetail);
        }
        return DataReturn.ok();
    }

    @PostMapping(value = "/upAndDownProcess", produces = "application/json;charset=UTF-8")
    public DataReturn upAndDownProcess(@RequestBody UpAndDownLineDTO upAndDownLineDTO) {
        Map<String, Object> loginOn = new HashMap<>(2);
        loginOn.put("id", upAndDownLineDTO.getUserId());
        loginOn.put("status", upAndDownLineDTO.getUpAndDown());
        //推送消息到web端
        SendMessageDTO sendMessageDTO = new SendMessageDTO();
        sendMessageDTO.setFlag("web");
        sendMessageDTO.setMsg(JSON.toJSONString(DataReturn.ok(MsgIdentificationConstants.UAV_PATROL_SIGN, loginOn)));
        communicateFeignClient.sendMsg(sendMessageDTO);
        return DataReturn.ok();
    }

}
